import styles from './index.less';

import { useEffect, useMemo, useCallback } from 'react';
import { useLocation, useUpdateEffect } from 'react-use';

interface PropsType {
  data: { label: string; value: string; }[];
  defaultTab?: string;
}

const Tabs: React.FC<PropsType> = ({ data, defaultTab }) => {
  const locationState = useLocation();

  const curTab = useMemo(() => {
    const urlSearchParams = new URLSearchParams(locationState.search);
    return urlSearchParams.get('type') || defaultTab || data[0].value || null;
  }, [locationState]);

  useEffect(() => {
    onClickTab(curTab);
    const st = setTimeout(() => {
      scrollTabToPosition();
    }, 100);
    return () => {
      clearTimeout(st);
    };
  }, []);

  useUpdateEffect(() => {
    scrollTabToPosition();
  }, [curTab]);

  // tab点击
  const onClickTab = useCallback((type) => {
    const { pathname, search, hash } = window.location;
    const typeIsExist = data.find((item) => item.value === type);
    const urlSearchParams = new URLSearchParams(search);
    urlSearchParams.delete('type');
    urlSearchParams.set('type', typeIsExist ? type : data[0].value);
    const searchString = urlSearchParams.toString();
    window.history.replaceState({}, '', `${pathname}${searchString ? `?${searchString}` : ''}${hash}`);
  }, []);

  // tab滚动定位
  const scrollTabToPosition = useCallback(() => {
    const scrollDom = document.getElementById('tab_scroll');
    const tabDom = document.getElementById(`tab_${curTab}`);
    const winW = document.body.clientWidth;
    const scrollLeft = scrollDom?.scrollLeft || 0;
    const offsetLeft = tabDom?.offsetLeft || 0;
    scrollDom?.scrollBy(offsetLeft - scrollLeft - winW / 3, 0);
  }, [curTab]);

  return (
    <div className={styles['tabs']}>
      <ul className={styles['tab-list']} id='tab_scroll'>
        {data.map((item, index) => {
          return (
            <li
              key={index}
              className={`${styles['tab-item']} ${curTab === item.value ? styles['actived'] : ''}`}
              id={`tab_${item.value}`}
              onClick={() => onClickTab(item.value)}>
              {item.label}
            </li>
          );
        })}
      </ul>
    </div>
  );
};

export default Tabs;
